package com.dong.cloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author DJ
 * @description 网关日志过滤器
 * @date 2022/1/24 11:06 下午
 **/
@Component
@Slf4j
public class MyLogGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("************ come in MyLogGlobalFilter" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (StringUtils.isBlank(username)) {
            log.info("************用户名为null, 非法用户, o(╥﹏╥)o");
            // 设置一个响应：不被接受的
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            // 执行完毕
            return exchange.getResponse().setComplete();
        }
        // 正常情况 过滤器链继续执行
        return chain.filter(exchange);
    }

    /**
     * 执行顺序 值越小 优先级越高
     *
     * @author DJ
     * @date 11:06 下午 2022/1/24
     * @param
     * @return int
     **/
    @Override
    public int getOrder() {
        return 0;
    }
}
